import React, { Component } from 'react'
import './Login.css'
import { connect } from 'react-redux' // 连接store
import cookies from 'js-cookies';
import { Redirect } from 'react-router-dom'
import styles from '../../assets/less/pass.less'
import logo from '../../assets/logo.png'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import {
   NavBar, // 顶部标题
   Form, Input, // 表单组件
   Button, // 按钮
   Toast, // 提示框
} from 'antd-mobile'
// 导入user中的action
import {
   loginOkAction,
   getUserInfoToCookieAction
} from '../../redux/user/actions'
// 导入api
import { loginAxios } from '../../api/api'

class Login extends Component {
   state = {
      loginInfo: {
         username: '', // 账号
         password: '', // 密码
      },
      visible: false, // 密码可见
      loginOk: false // 是否加载完成
   }
   /* 存储表单数据 */
   saveFormData = (key, val) => {
      this.setState({
         loginInfo: {
            ...this.state.loginInfo,
            [key]: val
         }
      })
   }
   /* 跳转路由 */
   goTo = (path) => {
      this.props.history.push(path)
   }
   /* 设置密码可见状态 */
   setVisible = (val) => {
      return () => {
         this.setState({ visible: val })
      }
   }
   /* 执行登录操作 */
   doLogin = () => {
      // 提交表单数据给action
      loginAxios(this.state.loginInfo).then(res => {
         // 数据校验
         for (let key in this.state.loginInfo) {
            if (!this.state.loginInfo[key]) return Toast.show({ content: '请完整填写用户信息' })
         }
         if (res.msg === '用户名或密码不正确!') {
            Toast.show({
               icon: 'fail',
               content: '用户名或密码不正确'
            })
         } else {
            Toast.show({
               icon: 'success',
               content: '登录成功'
            })
            // 存储用户的状态数据
            this.props.loginOkAction(res.data)
            // 跳转到主页
            this.goTo('/' + res.data.type)
         }
      })
   }
   /* 根据cookie实现自动登录 */
   componentDidMount() {
      // 自动登录功能的实现
      if (cookies.getItem('userid')) {
         this.props.getUserInfoToCookieAction()
         let timer = setInterval(() => {
            this.setState(() => ({}), () => {
               if (this.props.userInfo) {
                  this.setState({loginOk: true})
                  clearInterval(timer)
               }
            })
         }, 200)
      }
   }
   render() {
      if (this.state.loginOk) {
         return <Redirect to={`/${this.props.userInfo.type}`}/>
      }
      const { username, password } = this.state.loginInfo
      return (
         <div className='login-view'>
            <NavBar backArrow={false}>登录</NavBar>
            <div className="logo">
               <img src={logo} alt="" />
            </div>
            {/* 表单数据 */}
            <Form layout='horizontal'>
               <Form.Item label='用户名：' name='username'>
                  <Input placeholder='请输入用户名' clearable value={username} onChange={(val) => this.saveFormData('username', val.trim())} />
               </Form.Item>
               <Form.Item
                  label='密&nbsp;&nbsp; 码：' name='password'
                  extra={
                     <div className={styles.eye}>
                        {!this.state.visible ? (
                           <EyeInvisibleOutline onClick={this.setVisible(true)} />
                        ) : (
                           <EyeOutline onClick={this.setVisible(false)} />
                        )}
                     </div>
                  }
               >
                  <Input
                     placeholder='请输入密码'
                     clearable
                     type={this.state.visible ? 'text' : 'password'}
                     value={password}
                     onChange={(val) => this.saveFormData('password', val.trim())}
                  />
               </Form.Item>
               <Button block size='large'
                  style={{
                     '--background-color': '#118EE8',
                     '--text-color': '#fff'
                  }}
                  onClick={this.doLogin}
               >登录</Button>
               <Button block size='large' style={{ '--border-radius': '0px' }} onClick={() => this.goTo('/register')}>还没有账号？</Button>
            </Form>
         </div>
      )
   }
}
// 将store与组件连接
export default connect(
   state => ({ userInfo: state.user }),
   { loginOkAction, getUserInfoToCookieAction }
)(Login)